package com.scalar.chiptrack.sales.actions.quote;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;

import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.operations.packingslip.PackingSlipComparator;
import com.scalar.chiptrack.sales.ContactPerson;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.Quotation;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.SubTotal;
import com.scalar.chiptrack.sales.TermsAndConditions;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.quote.QuotationDAO;
import com.scalar.chiptrack.sales.forms.quote.SendQuoteMailForm;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.PDFGenerator;
import com.scalar.chiptrack.utils.StringUtils;

/**
 * Author: Prabhanjan
 * Date: May 21, 2004
 * Time: 1:35:11 AM
 */

public class SendQuoteMailAction extends ChipTrackAction
{
    public SendQuoteMailAction ()
    {
    }

    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response )
    {

        HashMap info = new HashMap ();
        request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
        HashMap errors = new HashMap ();
        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
        SendQuoteMailForm sendQuoteMailForm = ( SendQuoteMailForm ) form;
        String quotationId = request.getParameter ( "quotationId" );
        String showAgain = request.getParameter ( "showAgain" );
        Quotation quotation = null;
        request.setAttribute ( "quotationId", quotationId );
        String quotationNo = null;
        String email = null;
        String customerId = null;
        String customerName = null;
        ArrayList quotationContactPersons = null;
        String types[] = null;

        try
        {

            if ( quotationId != null )
            {
                quotation = QuotationDAO.loadQuotation( quotationId, false );
                quotationNo = quotation.getQuotationNo();
                email = quotation.getEmail ();
                customerId = Integer.toString ( quotation.getCustomerId () );
                customerName = quotation.getCustomerName ();

            }
        }
        catch ( ScalarException se )
        {
            System.out.println ( "Exception while loading Quote No..... " );
            se.getRootCause ().printStackTrace ();
        }

        String mimeType = sendQuoteMailForm.getAttachMIMEType ();
        if ( ( mimeType == null ) || ( mimeType.trim ().length () == 0 ) )
        {
            mimeType = "PDF";
            sendQuoteMailForm.setAttachMIMEType ( "PDF" );
        }

        String subject = null;
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, "/sendQuoteMail.do?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }

        request.setAttribute( "showAgain", showAgain );

        boolean success = false;
        String action = request.getParameter ( "action" );

        String from = user.getEmail ();

        if ( ( action != null ) && ( action.equalsIgnoreCase ( "save" ) ) )
        {
            try
            {
                String to = StringUtils.concatStrings ( sendQuoteMailForm.getToUsers (), Mailer.EMAIL_SEPARATOR );
                String cc = StringUtils.concatStrings ( sendQuoteMailForm.getCcUsers (), Mailer.EMAIL_SEPARATOR );
                String bcc = StringUtils.concatStrings ( sendQuoteMailForm.getBccUsers (), Mailer.EMAIL_SEPARATOR );

                to = Mailer.getNotifiableEmails ( to, false );
                cc = Mailer.getNotifiableEmails ( cc, false );
                bcc = Mailer.getNotifiableEmails ( bcc, false );
                if ( cc == null )
                {
                    sendQuoteMailForm.setCcUsers ( null );
                }
                if ( bcc == null )
                {
                    sendQuoteMailForm.setBccUsers ( null );
                }

                subject = sendQuoteMailForm.getSubject ();

                if ( subject == null )
                {
                    subject = " Quote Details for : " + customerId;
                }
                sendQuoteMailForm.setSubject ( subject );
                String message = sendQuoteMailForm.getMessage ().replaceAll( "\n", "<br>" );

                String host = request.getHeader ( "HOST" );

                String quoteAckFile = null;


                    if( "PDF".equalsIgnoreCase( mimeType  ) )
                    {
                        quoteAckFile = getQuoteAckPDFFile( quotationId ) ;
                    }
                    else
                    {
                        quoteAckFile = getQuoteAckHtmlFile ( host, quotationId , request);
                    }


                String[] mailAttachments = null;

                String isConfirm = ( String ) session.getAttribute ( "isConfirm" );
                String sysAdminEmail = ConfigManager.getSysAdminEmail ();
                String companyEmailId = sysAdminEmail.substring ( sysAdminEmail.indexOf ( "@" ) + 1, sysAdminEmail.length () );
                if ( isConfirm == null )
                {
                    to = Mailer.getNotifiableEmails ( to, false );
                    cc = Mailer.getNotifiableEmails ( cc, false );
                    bcc = Mailer.getNotifiableEmails ( bcc, false );
                    InternetAddress[] toAddress = null;
                    InternetAddress[] ccAddress = null;
                    InternetAddress[] bccAddress = null;

                    String emailIds = "";
                    if ( to != null )
                    {
                        toAddress = InternetAddress.parse ( to );
                        for ( int i = 0; i < toAddress.length; i++ )
                        {
                            InternetAddress temp = toAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if ( emailIds == "")
                                {
                                  emailIds = emailIds + temp.getAddress ();
                                }
                                else
                                {
                                  emailIds = emailIds + ", "+ temp.getAddress ();
                                }

                            }
                        }
                    }
                    if ( cc != null )
                    {
                        ccAddress = InternetAddress.parse ( cc );
                        for ( int i = 0; i < ccAddress.length; i++ )
                        {
                            InternetAddress temp = ccAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if ( emailIds == "")
                                {
                                  emailIds = emailIds + temp.getAddress ();
                                }
                                else
                                {
                                  emailIds = emailIds + ", "+ temp.getAddress ();
                                }
                            }
                        }
                    }
                    if ( bcc != null )
                    {
                        bccAddress = InternetAddress.parse ( bcc );
                        for ( int i = 0; i < bccAddress.length; i++ )
                        {
                            InternetAddress temp = bccAddress[i];
                            String address = temp.getAddress ();
                            if ( address.indexOf ( companyEmailId ) == -1 )
                            {
                                if ( emailIds == "")
                                {
                                  emailIds = emailIds + temp.getAddress ();
                                }
                                else
                                {
                                  emailIds = emailIds + ", "+ temp.getAddress ();
                                }
                            }
                        }
                    }

                    if ( emailIds.trim ().length () > 0 )
                    {
                        errors.put ( "The following e-mails are going out of the company. Please confirm to send them.", null );
                        info.put ( "Emails", emailIds );

                        session.setAttribute ( "isConfirm", "True" );
                        return mapping.findForward ( "success" );
                    }

                }
                mailAttachments = new String[]{quoteAckFile};
                Mailer.send ( from, to, cc, bcc, subject, message, mailAttachments, Mailer.CONTENT_TYPE_HTML, false );
                info.put ( "Email has been sent successfully", null );
                session.removeAttribute ( "isConfirm" );
            }
            catch ( Exception se )
            {
                success = false;
                String errMessage = "Error";
                errors.put ( errMessage, "Could not send Email. Please check the EmailId" );
                se.printStackTrace ();
                return mapping.findForward ( "success" );
            }

            return ( mapping.findForward ( "sendQuoteMailView" ) );
        }
        else if ( "showQuoteContactPersonDetails".equalsIgnoreCase ( action ) )
        {
            try
            {
                String value = ( String ) session.getAttribute ( "QuoteShowAgain" );
                if ( "True".equals ( value ) )
                {
                    quotationContactPersons = ( ArrayList ) session.getAttribute ( "QuoteContactPersons" );
                }
                else
                {
                    quotationContactPersons = CustomerDAO.getAllContactPersonsWithEmails ( null, quotation );
                    int contactPersonsSize = 0;
                    int i = 0;
                    if( quotationContactPersons != null )
                    {
                        contactPersonsSize = quotationContactPersons.size();
                    }
                    types = new String[ contactPersonsSize + 2 ];
                    for ( i = 0; i < contactPersonsSize; i++ )
                    {
                       types[i] = "Contact Person";
                    }
                   int billingAddressId = SalesOrderDAO.getDefaultBillingAddressId( quotation.getCustomerId() );
                   String customerEmail    = CustomerDAO.getAddress( billingAddressId ).getEmail();

                   if ( customerEmail != null && !"".equals(customerEmail.trim()) )
                   {
                       ContactPerson customer = new ContactPerson();
                       customer.setContactPerson(quotation.getCustomerName());
                       customer.setEmail( customerEmail );
                       quotationContactPersons.add(customer);
                       types[i++] = "Customer";
                   }

                   session.setAttribute ("types",types);
                }
            }
            catch ( ScalarException e )
            {
                e.printStackTrace ();
            }
            session.setAttribute ( "QuoteShowAgain", "False" );
            request.setAttribute ( "QuoteContactPersons", quotationContactPersons );
            return ( mapping.findForward ( "showQuoteContactPersons" ) );
        }
        else if ( "displayMailIds".equalsIgnoreCase ( action ) )
        {
            try
            {
                quotationContactPersons = CustomerDAO.getAllContactPersonsWithEmails ( null, quotation );
                int billingAddressId = SalesOrderDAO.getDefaultBillingAddressId( quotation.getCustomerId() );
                String customerEmail    = CustomerDAO.getAddress( billingAddressId ).getEmail();
                if ( customerEmail != null && !"".equals(customerEmail.trim()) )
                {
                    ContactPerson customer = new ContactPerson();
                    customer.setContactPerson(quotation.getCustomerName());
                    customer.setEmail( customerEmail );
                    quotationContactPersons.add(customer);
                }
                for ( int i = 0; i < quotationContactPersons.size (); i++ )
                {
                    ContactPerson contactPerson = ( ContactPerson ) quotationContactPersons.get ( i );

                    if ( request.getParameter ( "selectedValue" + i ) != null )
                    {
                        contactPerson.setIsChecked ( true );
                    }
                }
                session.setAttribute ( "QuoteContactPersons", quotationContactPersons );
                session.setAttribute ( "QuoteShowAgain", "True" );
            }
            catch ( Exception se )
            {
                System.out.println ( "Exception while loading Quote acknowledgement emails.. " );
            }
            return ( mapping.findForward ( "success" ) );
        }

        try
        {
            subject = sendQuoteMailForm.getSubject ();
            if ( subject == null )
            {
                subject = customerName + " Quote Details for  " + quotationNo;
            }
            sendQuoteMailForm.setSubject ( subject );

            /*String[] mailTo = new String[1];
            if(( email == null ) || ( email.equalsIgnoreCase("") ))
            {
                mailTo[0] = "";
            }
            else
            {
                mailTo[0] = email ;
            }
            sendQuoteMailForm.setToUsers ( mailTo );*/

            if( sendQuoteMailForm.getToUsers() == null )
            {
                sendQuoteMailForm.setToUsers( UserDAO.loadAllApproversEmails( null, -1, "Quotation" ) );
            }
        }

        catch ( Exception se )
        {
            System.out.println ( "Exception while loading Quote emails.. " );
        }

        session.removeAttribute ( "QuoteShowAgain" );
        session.removeAttribute ( "isConfirm" );

        sendQuoteMailForm.setCustomerId ( quotation.getCustomerId () );
        request.setAttribute ( "sendQuoteMailForm", sendQuoteMailForm );
        return ( mapping.findForward ( "success" ) );
    }

    public static String getQuoteAckHtmlFile ( String host, String quotationId, HttpServletRequest request ) throws ScalarException
    {
        String filePath = null;
        Quotation quotation = null;
        if ( quotationId != null )
        {
            quotation = QuotationDAO.loadQuotation(quotationId, false);
        }

        ArrayList presentList = QuotationDAO.loadOrderLineItemsWithCustomerPartNo(quotation.getQuotationId(), quotation.getCustomerId());
        int odmId = quotation.getOdmId() ;

        String quotationAsHtml = formatAsHTML ( host, quotation, presentList, request );

        if ( quotationAsHtml == null )
        {
            return filePath;
        }

        FileWriter fWriter = null;
        File psAttachment = null;

        try
        {
            File tempDir = new File ( "chiptrac_temp_dir" ).getCanonicalFile ();
            tempDir.mkdir ();

            String salesAttachmentFileName = null;
            String quotationNo = quotation.getQuotationNo();

            salesAttachmentFileName = "Quote_Details#  " + quotationNo + ".html";

            psAttachment = new File ( tempDir.getCanonicalPath (), salesAttachmentFileName );
            psAttachment.deleteOnExit ();

            if ( ( psAttachment.exists () == true ) || ( psAttachment.createNewFile () == true ) )
            {
                fWriter = new FileWriter ( psAttachment, false );

                fWriter.write ( quotationAsHtml );

                fWriter.close ();
                fWriter = null;

                filePath = psAttachment.getAbsolutePath ();
            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating Quote html file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return filePath;
    }


    public static String formatAsHTML ( String host, Quotation quotation, ArrayList presentList, HttpServletRequest request ) throws ScalarException
    {
        StringBuffer buf = new StringBuffer ( 2098 );
        String bgColor = "bgcolor='#FFFFFF'";
        String mfgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mfgPartNumber" );
        if ( mfgPartNumberLabel == null )
        {
            mfgPartNumberLabel = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
        }
        String customerPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.customerPartNumber" );
        if ( customerPartNumberLabel == null )
        {
            customerPartNumberLabel = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
        }
        String endCustomerLabel = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.sales.endCustomer");
        if ( endCustomerLabel == null )
        {
             endCustomerLabel = "Error in End Customer";
        }
        String endUserLabel = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.sales.endUser");
        if ( endUserLabel == null )
        {
             endUserLabel = "Error in End User";
        }
        String requestedPriceLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.requestedPrice" );
        if ( requestedPriceLabel == null )
        {
            requestedPriceLabel = Labels.DEFAULT_REQUESTED_PRICE_LABEL;
        }
        String custResalePriceLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.customerResalePrice" );
        if ( custResalePriceLabel == null )
        {
            custResalePriceLabel = Labels.DEFAULT_CUST_RESALE_PRICE_LABEL;
        }
        String priceLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.price" );
        if ( priceLabel == null )
        {
            priceLabel = Labels.DEFAULT_PRICE_LABEL;
        }
        String suggResalePriceLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.suggestedResalePrice" );
        if ( suggResalePriceLabel == null )
        {
            suggResalePriceLabel = Labels.DEFAULT_SUGG_RESALE_PRICE_LABEL;
        }
        String requestedQuotationDetialsLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.quotation.quoteDetails" );
        if ( requestedQuotationDetialsLabel == null )
        {
            requestedQuotationDetialsLabel = Labels.DEFAULT_QUOTATION_DETAILS_LABEL;
        }
        String requestedOrderBYLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.quotation.orderedBy" );
        if ( requestedOrderBYLabel == null )
        {
            requestedOrderBYLabel = Labels.DEFAULT_QUOTATION_ORDER_BY_LABEL;
        }
        String requestedOrderDateLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.quotation.orderDate" );
        if ( requestedOrderDateLabel == null )
        {
            requestedOrderDateLabel = Labels.DEFAULT_QUOTATION_ORDER_DATE_LABEL;
        }
        String requestedSalesPersonLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.quotation.salesPerson" );
        if ( requestedSalesPersonLabel == null )
        {
            requestedSalesPersonLabel = Labels.DEFAULT_QUOTATION_SALES_PERSON_LABEL;
        }
        String requestedRegionalRepLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.quotation.regionalRep" );
        if ( requestedRegionalRepLabel == null )
        {
            requestedRegionalRepLabel = Labels.DEFAULT_QUOTATION_REGIONAL_REP_LABEL;
        }

        buf.append ( "<HTML><HEAD><TITLE>Scalarsoft - ChipTrac</TITLE>" );
        buf.append ( "<LINK href='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/stylesheets/scalarsoft.css' type=text/css rel=stylesheet>" );
        buf.append ( "<style type='text/css'>" );
        buf.append ( "a { text-decoration : none}" );
        buf.append ( "</style>" );
        if ( ! quotation.isApproved() )
        {
            buf.append ( "</HEAD><BODY " );
            buf.append ( "background='"+request.getScheme()+"://" + host + "/" + ConfigManager.getChipTracContext() + "/jsp/includes/images/not_approved_icon.gif' " );
            bgColor = "";
            buf.append (">");
        }
        else
        {
            buf.append ( "</HEAD><BODY "+ bgColor + "leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'>" );
        }

       /* if (!Constants.RELEASE_STATUS_APPROVED.equalsIgnoreCase( quotation.getStatus() ) )
        {
            buf.append ( "background='"+request.getScheme()+"://" + host + "/" + ConfigManager.getChipTracContext() + "/jsp/includes/images/cancelled_icon.gif' " );
            bgColor = "";
        }
        buf.append ( "</HEAD><BODY bgColor="+ bgColor + "leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'>" );

        if (!Constants.RELEASE_STATUS_APPROVED.equalsIgnoreCase( quotation.getStatus()))
        {
            buf.append ( "background='"+request.getScheme()+"://" + host + "/" + ConfigManager.getChipTracContext() + "/jsp/includes/images/cancelled_icon.gif' " );
            bgColor = "";
        }*/

        buf.append ( "<!-- from here your body starts -->" );
        buf.append ( "<Div1><table width='98%' cellspacing='0' cellpadding='0' border=0 align=center>" );
        buf.append ( " <tr>" );
        buf.append ( "<td width='35%' align='left' valign='top'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/scalar_logo.jpg' height='72' width='180' border=0></td>" );
        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
        Address clientAddress = quotation.getClientAddressAsObject ();
        buf.append ( "<td width='27%' align='center' class='NArialL'>");
        buf.append ( "<table border=0 cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr><td align='center'><h2>"+ requestedQuotationDetialsLabel +"</h2></td></tr>" );
        buf.append ( "<tr><td align='center' class='NArialL'>" ).append( quotation.getClientName() ).append( "</td></tr>" );
        buf.append ( "<tr><td align='center' class='NArialL'>" ).append ( quotation.getClientAddressAsHTML() ).append ( "</td></tr>" );
        buf.append ( "</table></td>" );
        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
        buf.append ( " <td width='36%' align=center><font class='NArialW'>" );
        buf.append ( " </font></td>" );
        buf.append ( " </tr>" );
        buf.append ( "<tr><td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td></tr>" );
        String customerName = quotation.getCustomerName ();
        if ( quotation.getCustomerName ().equals ( quotation.getContactPerson () ) )
        {
            customerName = null;
        }
        Address address = quotation.getBillingAddressAsObject ();
		String addressValue = address.getAddressAsString();

        buf.append ( " <tr>" );
        buf.append ( " <td  colspan='5' width='100%'>" );
        buf.append ( " <table border='0' width='100%'>" );
        buf.append ( " <tr>" );
        buf.append ( " <td height='100%' width='33%'>" );
        buf.append ( " <table border='1' width='100%' height='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( " <tr height=20><td class='NArialL' bgcolor='#DEE1E2'>" + requestedOrderBYLabel +  ": </td></tr> " );
        buf.append ( " <tr height=20><td  valign='top' class='NArialL' bgcolor='#FFFFEE'>" );
        buf.append ( " <table width='100%' class='NArialL' height=80 cellspacing='0' cellpadding='0'>" );
        buf.append ( " <tr><td>");
		buf.append (  quotation.getBillingAddressAsHTML() );
		buf.append ( " </td></tr>"  );
        buf.append ( " </table></td>" );
        buf.append ( " </tr></table></td>" );
        buf.append ( " <td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );

        buf.append ( " <td height='100%' width='30%'>" );
        buf.append ( " <table border='1' width='100%' height='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( " <tr height=20><td class='NArialL' bgcolor='#DEE1E2'>Bill To :</td></tr>" );
        buf.append ( " <tr height=20><td  valign='top' class='NArialL' bgcolor='#FFFFEE'>" );
        buf.append ( " <table width='100%' class='NArialL' height=80 cellspacing='0' cellpadding='0'>" );
        buf.append ( " <tr><td>");
		buf.append (  quotation.getBillingAddressAsHTML() );
		buf.append ( " </td></tr>"  );
        buf.append ( " </table></td>" );
        buf.append ( " </tr></table></td>" );
        buf.append ( " <td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );

        buf.append ( " <td height='100%' width='38%'>" );
        buf.append ( " <table border='1' width='100%' height='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( " <tr height=20><td class='NArialL' bgcolor='#DEE1E2'>Ship To :</td></tr>" );
        buf.append ( " <tr height=20><td  valign='top' class='NArialL' bgcolor='#FFFFEE'>" );
        buf.append ( " <table width='100%' class='NArialL' height=80 cellspacing='0' cellpadding='0'>" );
        buf.append ( " <tr><td>");
        buf.append (  quotation.getShippingAddressAsHTML() );
        buf.append ( " </td></tr>"  );
        buf.append ( " </table></td>" );
        buf.append ( " </tr></table></td>" );

        buf.append ( " </tr>" );
        buf.append ( " </table>" );
        buf.append ( " </td>" );
        buf.append ( " </tr>" );


        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td></tr>" );

        buf.append ( " <tr>" );
        buf.append ( " <td  colspan='5' width='100%'>" );
        buf.append ( " <table border='0' width='100%'>" );
        buf.append ( " <tr>" );
        buf.append ( " <td height='100%' width='33%'>" );
        buf.append ( " <table border='1' width='100%' class='NArialL' height='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( " <tr height=20><td bgcolor='#DEE1E2'>Quote #</td><td bgcolor='#DEE1E2'> " + requestedOrderDateLabel + "</td></tr>" );
        buf.append ( " <tr height=20>" );
        buf.append ( " <td bgcolor='#FFFFEE'>" );
        buf.append (  quotation.getQuotationNo() );
        buf.append ( " </td" );
        buf.append ( " <td bgcolor='#FFFFEE'>" + quotation.getBookingdateAsString () + "&nbsp;</td>" );
        buf.append ( " </tr></table></td>" );
        buf.append ( " <td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );

        buf.append ( " <td height='100%' width='30%'>" );
        buf.append ( " <table border='1' width='100%' class='NArialL' height='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( " <tr height=20><td bgcolor='#DEE1E2'> Quotation Expires On </td><td bgcolor='#DEE1E2'>Ship Via</td></tr>" );
        buf.append ( " <tr height=20>");
        buf.append ( " <td bgcolor='#FFFFEE'>" + quotation.getExpiryDate()  + "&nbsp;</td>" );
        buf.append ( " <td bgcolor='#FFFFEE'>" + quotation.getShippingMethod () + "&nbsp;</td>" );
        buf.append ( " </tr></table></td>" );
        buf.append ( " <td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );

        buf.append ( " <td height='100%' width='38%'>" );
        buf.append ( " <table border='1' class='NArialL' width='100%' height='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( " <tr height=20><td bgcolor='#DEE1E2'>" + requestedSalesPersonLabel + " </td><td bgcolor='#DEE1E2'> " + requestedRegionalRepLabel + "</td><td bgcolor='#DEE1E2'> Del Terms</td><td bgcolor='#DEE1E2'>Pay Terms</td></tr>" );
        buf.append ( " <tr height=20>");
        buf.append ( " <td bgcolor='#FFFFEE'>" + quotation.getSalesPerson() + "&nbsp;</td>" );
        buf.append ( " <td bgcolor='#FFFFEE'>" + quotation.getRegionalRep() + "&nbsp;</td>" );
        buf.append ( " <td bgcolor='#FFFFEE'>" + quotation.getDeliveryTerms() + "&nbsp;</td>" );
        buf.append ( " <td bgcolor='#FFFFEE'>" + ( quotation.getShippingTerms ().trim ().equals ( "-1" ) ? "" : quotation.getShippingTerms () ) + "&nbsp;</td>" );
        buf.append ( " </tr></table></td>" );
        buf.append ( " </tr>" );
        buf.append ( " </table>" );
        buf.append ( " </td>" );
        buf.append ( " </tr>" );

        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tr>" );
        buf.append ( "<tr><td colspan=5 class='NArialL'><U>Comments:</U></td></tR>" );
        buf.append ( "<tr><td colspan=5 class='NArialL' bgcolor='#FFFFEE'>" + quotation.getComments () + "&nbsp;</td></tr>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tr>" );
        buf.append ( "<tr><td colspan='5'>" );

        buf.append ( "<table width='100%' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr height=20>" );
        buf.append ( "<td width='8%' class='NArialL' bgcolor='#DEE1E2' align=center>PO Line#</td>" );
        buf.append ( "<td width='5%'  class='NArialL' bgcolor='#DEE1E2' align=center>Req Qty</td>" );
        int additionalColumns = 0;
        if(ConfigManager.isShowQuoteMinOrderQty()) {
            additionalColumns++;
            buf.append ( "<td width='5%'  class='NArialL' bgcolor='#DEE1E2' align=center>Min Order Quantity</td>" );
        }
        buf.append ( "<td width='2%'  class='NArialL' bgcolor='#DEE1E2' align=center>UM</td>" );
        buf.append ( "<td width='13%' class='NArialL' bgcolor='#DEE1E2' align=center>" + mfgPartNumberLabel + "</td>" );
        buf.append ( "<td width='13%' class='NArialL' bgcolor='#DEE1E2' align=center>" + customerPartNumberLabel + "</td>" );
        buf.append ( "<td width='18%' class='NArialL' bgcolor='#DEE1E2' align=center>Description</td>" );
        buf.append ( "<td width='10%' class='NArialL' bgcolor='#DEE1E2' align=center>Requested Dock Date</td>" );
        buf.append ( "<td width='8%'  class='NArialL' bgcolor='#DEE1E2' align=center>Lead Time</td>" );
        buf.append ( "<td width='8%'  class='NArialL' bgcolor='#DEE1E2' align=center>Taxable<br>Yes or No</td>" );

        if ( quotation.isDistributor() )
        {
            if ( ConfigManager.isShowQuoteRequestedPrice() )
            {
                additionalColumns++;
                buf.append ( "<td width='5%'  class='NArialL' bgcolor='#DEE1E2' align=center>" + requestedPriceLabel + "</td>" );
            }
            if ( ConfigManager.isShowQuoteCustResalePrice() )
            {
                additionalColumns++;
                buf.append ( "<td width='5%'  class='NArialL' bgcolor='#DEE1E2' align=center>" + custResalePriceLabel + "</td>" );
            }
        }
        buf.append ( "<td width='5%'  class='NArialL' bgcolor='#DEE1E2' align=center>" + priceLabel+ "</td>" );
        if ( quotation.isDistributor() )
        {
            if ( ConfigManager.isShowQuoteSuggResalePrice() )
            {
                additionalColumns++;
                buf.append ( "<td width='5%'  class='NArialL' bgcolor='#DEE1E2' align=center>" + suggResalePriceLabel + "</td>" );
            }
        }

        buf.append ( "<td width='11%' class='NArialL' bgcolor='#DEE1E2' align=center>Extended<br> Price</td>" );

        buf.append ( "</tr>" );

        LineItem lineItem = null;
        ArrayList presentListWithSubtotals = QuotationViewAction.loadLineItemsWithSubTotals ( presentList );

        for ( int i = 0; i < presentListWithSubtotals.size (); i++ )
        {
            HashMap hashMap = ( HashMap ) presentListWithSubtotals.get ( i );
            Iterator iterator = hashMap.keySet ().iterator ();
            while ( iterator.hasNext () )
            {
                ArrayList list = ( ArrayList ) iterator.next ();
                SubTotal subTotal = ( SubTotal ) hashMap.get ( list );
                String subTotalQty = subTotal.getSubTotalQty ();
                String subTotalAmt = subTotal.getSubTotalAmt ();

                int size = list.size ();
                for ( int j = 0; j < size; j++ )
                {
                    lineItem = ( LineItem ) list.get ( j );
                    buf.append ( "<tr height=20>" );
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getPoLineItemNo () + "&nbsp;</td>" );
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getQuantity () + "&nbsp;</td>" );
                    if(ConfigManager.isShowQuoteMinOrderQty()) {
                        buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getMinOrderQty () + "&nbsp;</td>" );
                    }
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>ea</td>" );
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center nowrap>" + lineItem.getManufacturingPartNo () + "&nbsp;</td>" );
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center nowrap>" + lineItem.getCustomerPartNo () + "&nbsp;</td>" );
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' wrap>" + lineItem.getLineItemDescription () + "&nbsp;</td>" );
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getRequestDate () + "&nbsp;</td>" );
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + (lineItem.getLeadTime() == null ? "" : lineItem.getLeadTime()) + "&nbsp;</td>" );
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getIsTaxableAsString () + "&nbsp;</td>" );
                    if ( quotation.isDistributor() )
                    {
                        if ( ConfigManager.isShowQuoteRequestedPrice() )
                        {
                            buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=right>" + lineItem.getReqPriceAsString() + "</td>" );
                        }
                        if ( ConfigManager.isShowQuoteCustResalePrice() )
                        {
                            buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=right>" + lineItem.getCustResaleAsString() + "</td>" );
                        }
                    }
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=right>" + lineItem.getUnitPriceAsString () + "&nbsp;</td>" );
                    if ( quotation.isDistributor() )
                    {
                        if ( ConfigManager.isShowQuoteSuggResalePrice() )
                        {
                            buf.append ( "<td  bgcolor='#FFFFEE'  class='NArialL' align=right>" + lineItem.getSuggResaleAsString() + "</td>" );
                        }
                    }
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=right>" + lineItem.getExtendedPriceForQuoteAsString() + "&nbsp;</td>" );
                    buf.append ( "</tr>" );
                }
                buf.append ( "<tr>" );
                buf.append ( "<td colspan='1'  bgcolor='#FFFFFF' class='NArialL' align='right'>Sub Total</td>" );
                buf.append ( "<td colspan='1' bgcolor='#FFFFFF' class='NArialL' align='center'>" + subTotalQty + "&nbsp;</td>" );
                buf.append ( "<td colspan='" + (8+additionalColumns) + "' >&nbsp;</td>" );
                buf.append ( "<td colspan='1' bgcolor='#FFFFFF' class='NArialL' align='right'>" + subTotalAmt + "&nbsp;</td>" );
                buf.append ( "</tr>" );
            }
        }
        buf.append ( "</table>" );
        buf.append ( "</td></tr>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );

        buf.append ( "<tr>" );

        buf.append ( "<td valign='top' align='left' width='35%'>" );
        buf.append ( "<table width='90%' border='1' align='left' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' >" + endCustomerLabel + "</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' >" + endUserLabel + "</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr>" );
        buf.append ( "<td class='NArialL' bgcolor='#FFFFEE' >" + quotation.getOdm() + "&nbsp;</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#FFFFEE' >" + quotation.getEndCustomer() + "&nbsp;</td>" );
        buf.append ( "</tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );

        buf.append ( "<td colspan='4' align='right' width='65%'>" );
        buf.append ( "<table width='40%' border='1' align='right' bordercolor='#000000'  cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr>" );
        buf.append ( "<td width='62%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height='1'></td>" );
        buf.append ( "<td width='38%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height='1'></td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL'>Total</td>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align='right'>" + quotation.getFinalSubTotalAsString() + "&nbsp;</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL'>Sales Tax</td>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align='right'>" + quotation.getFinalSalesTaxAsString() + "&nbsp;</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL'>Freight</td>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align='right'>" + quotation.getFrieghtAsString() + "&nbsp;</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL'>" + quotation.getMiscName () + "</td>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align='right'>" + quotation.getMiscAsString() + "&nbsp;</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL'>Balance Due</td>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align='right'>" + quotation.getFinalOrderTotalAsString() + "&nbsp;</td>" );
        buf.append ( "</tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );

        buf.append ( "</tr>" );
        buf.append ( "</table>" );
        if(ConfigManager.getShowTermsLabel())
        {
            buf.append ( "<table width='98%' bordercolor='#000000' cellspacing='0' cellpadding='2' border=0 align='center'>");
            buf.append ( "<TR>");
            buf.append ( "<TD width='98%' class='NArialRS'><p>" + Constants.TERMS_LABEL + "</p></TD>");
            buf.append ( "</TR>");
            buf.append ( "</table>");
        }
        buf.append ( "</td></tr>    " );
        buf.append ( "</table>" );
        buf.append ( "</p>" );
        if (ConfigManager.getShowTermsFromDB())
        {
            buf.append ( "<div style='page-break-after: always;'>&nbsp;</div><table width='100%' cellspacing='5' cellpadding='0' border=0 align=center>" );
            buf.append ( "<TR>" );
            buf.append ( "<TD width='100%' valign='top' colspan='3' class='viewdata2'><center><b>Terms And Conditions</b></center></TD>" );
            buf.append ( "</TR>" );
            buf.append ( "<TR>" );
            buf.append ( "<TD width='100%' valign='top' colspan='3' class='viewdata2'><center>" + quotation.getClientName () + "<BR>" );
            buf.append ( quotation.getClientAddressToLoad ( clientAddress ) + "</center></TD>" );
            buf.append ( "</TR>" );
            buf.append ( "<TR>" );
            buf.append ( "<TD width='100%' colspan='3' class='viewdata1'>&nbsp;</TD>" );
            buf.append ( "</TR>" );
            buf.append ( "<tr>" );

            ArrayList list = SalesDAO.loadTermsAndConditionsAsList ();
            if ( list != null )
            {
                for ( int i = 0; i < list.size (); i++ )
                {
                    TermsAndConditions terms = ( TermsAndConditions ) list.get ( i );
                    buf.append ( "<tr><td bgcolor='#DEE1E2' class='viewdata1'><U>" + ( i + 1 ) + ".&nbsp;" );
                    buf.append ( terms.getTermsTitle ().trim () + "</U>" + "&nbsp;" + terms.getTerms ().trim () + "</td></tr>" );
                }//for

            }//if


            buf.append ( "</tr></table>" );
        }
        else
        {
            buf.append ( "<p STYLE='page-break-after: always'></p>" );
            buf.append ( "<table width='98%' bordercolor='#000000' border='0' cellspacing='0' cellpadding='0' align='center'><TR>");
            buf.append ( "<TD width='100%' valign='top'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/Terms and Condition of Sale.jpg' width='1000'/></TD></TR></table>");
            buf.append ( "</body></html>" );
        }

        return buf.toString ();
    }


    public static String getQuoteAckPDFFile ( String quotationId ) throws ScalarException
    {
        String fileXMLPath = null;
        String filePDFPath = null;
        String fileXSLTPath = null;


        Quotation quotation = null;
        if ( quotationId != null )
        {
            quotation = QuotationDAO.loadQuotation( quotationId, false );
        }


        ArrayList presentList = QuotationDAO.loadOrderLineItemsWithCustomerPartNo(quotation.getQuotationId(), quotation.getCustomerId());
        int odmId = quotation.getOdmId() ;

        if ( presentList != null )
        {
            Collections.sort ( presentList, new PackingSlipComparator () );
        }

        String saAsXML = formatAsXML ( quotation, presentList );

        if ( saAsXML == null )
        {
            return fileXMLPath;
        }

        FileWriter fWriter = null;
        File saPDFAttachment = null;
        File saXML = null;

        try
        {
            // CREATE TEMPORARY ATTACHMENT FILE
            String mailingTempDir = ConfigManager.getMailerTempDir ();
            File tempDir = new File ( mailingTempDir ).getCanonicalFile ();
            tempDir.mkdir ();

            String salesNo = quotation.getQuotationNo ();
            String xmlFileName = "Quote_Details_" + salesNo + ".xml";
            String saAttachmentPDFFileName = "Quote_Details_" + salesNo + ".pdf";

            String xsltFileName = ConfigManager.getQuoteAckXml2PdfXslFile ();

            saXML = new File ( tempDir.getCanonicalPath (), xmlFileName );
            saXML.deleteOnExit ();

            saPDFAttachment = new File ( tempDir.getCanonicalPath (), saAttachmentPDFFileName );
            saPDFAttachment.deleteOnExit ();

            if ( ( saXML.exists () == true ) || ( saXML.createNewFile () == true ) )
            {
                fWriter = new FileWriter ( saXML, false );
                fWriter.write ( saAsXML );
                fWriter.close ();
                fWriter = null;

                fileXMLPath = saXML.getCanonicalPath ().toLowerCase ();
                filePDFPath = saPDFAttachment.getCanonicalPath ().toLowerCase ();

                boolean success = PDFGenerator.convertXML2PDF ( fileXMLPath, xsltFileName, filePDFPath );

            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating Quote Ack PDF file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return filePDFPath;
    }

    public static String formatAsXML ( Quotation quotation, ArrayList presentList ) throws ScalarException
    {
        StringBuffer buf = new StringBuffer ( 2098 );
        String requestedQuotationDetialsLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.quotation.quoteDetails" );
        if ( requestedQuotationDetialsLabel == null )
        {
            requestedQuotationDetialsLabel = Labels.DEFAULT_QUOTATION_DETAILS_LABEL;
        }
        String requestedOrderBYLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.quotation.orderedBy" );
        if ( requestedOrderBYLabel == null )
        {
            requestedOrderBYLabel = Labels.DEFAULT_QUOTATION_ORDER_BY_LABEL;
        }
        String requestedOrderDateLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.quotation.orderDate" );
        if ( requestedOrderDateLabel == null )
        {
            requestedOrderDateLabel = Labels.DEFAULT_QUOTATION_ORDER_DATE_LABEL;
        }
        String requestedSalesPersonLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.quotation.salesPerson" );
        if ( requestedSalesPersonLabel == null )
        {
            requestedSalesPersonLabel = Labels.DEFAULT_QUOTATION_SALES_PERSON_LABEL;
        }
        String requestedRegionalRepLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.quotation.regionalRep" );
        if ( requestedRegionalRepLabel == null )
        {
            requestedRegionalRepLabel = Labels.DEFAULT_QUOTATION_REGIONAL_REP_LABEL;
        }

        buf.append ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n" );
        if  (quotation.isApproved() )
        {
            buf.append ( "<quotationAcknowledgement approve='0'>" + "\n" );
        }
        else
        {
            buf.append ( "<quotationAcknowledgement approve='1'>" + "\n" );
        }
        //buf.append ( "<logo>d://chiptrack//jsp/includes/images/scalar_logo.jpg</logo>" + "\n" );
        buf.append ( "<approveImage>" + ConfigManager.getChipTracImagesDir () + ConfigManager.getCrossNotApprovedImage () + "</approveImage> \n" );
        buf.append ( "<logo>" + ConfigManager.getChipTracImagesDir () + ConfigManager.getScalarLogo () + "</logo>" + "\n" );
        buf.append ( "<labelQuoteDetails>" + requestedQuotationDetialsLabel +"</labelQuoteDetails>");
        buf.append ( "<selfAddress>" + "\n" );

        buf.append ( "<name><![CDATA[" + quotation.getClientName () + "]]></name>" + "\n" );
        Address clientAddress = quotation.getClientAddressAsObject ();

        buf.append ( "<address1><![CDATA[" + clientAddress.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + clientAddress.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + clientAddress.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + clientAddress.getAddress4 () + "]]></address4>" + "\n" );
        StringBuffer cityStateZip = new StringBuffer ( "" );

        if ( !clientAddress.getCity ().equals ( "" ) ) cityStateZip.append ( clientAddress.getCity () + ", " );
        if ( !clientAddress.getState ().equals ( "" ) ) cityStateZip.append ( clientAddress.getState () + " - " );
        if ( !clientAddress.getZipCode ().equals ( "" ) ) cityStateZip.append ( clientAddress.getZipCode () + ", " );
        cityStateZip.append ( clientAddress.getCountry () );

        buf.append ( "<cityStateZip><![CDATA[" + cityStateZip + "]]></cityStateZip>" + "\n" );

        StringBuffer phFax = new StringBuffer ();
        if ( !clientAddress.getPhoneNumber ().equals ( "" ) ) phFax.append ( "Tel:" + clientAddress.getPhoneNumber () + ", " );
        if ( !clientAddress.getFaxNumber ().equals ( "" ) ) phFax.append ( "Fax:" + clientAddress.getFaxNumber () );

        buf.append ( "<phoneFax><![CDATA[" + phFax + "]]></phoneFax>" + "\n" );


        buf.append ( "</selfAddress>" + "\n" );

        Address address = quotation.getBillingAddressAsObject ();

        String customerName = quotation.getCustomerName ();
        if ( quotation.getCustomerName ().equals ( quotation.getContactPerson () ) )
        {
            customerName = "";
        }


        buf.append ( "<orderByAddress>" + "\n" );
        buf.append("<labelOrderedBy>" +  requestedOrderBYLabel + "</labelOrderedBy>");
        if( quotation.getBillingAddressAsObject().getContactPerson() != null && quotation.getCustomerName().trim().length() !=0 )
        {
            if( ! quotation.getBillingAddressAsObject().getContactPerson().equals( quotation.getCustomerName() ) )
            {
                buf.append ( "<name><![CDATA[" + customerName + "]]></name>" + "\n" );
            }
        }

        buf.append ( "<contactPerson><![CDATA[" + address.getContactPerson () + "]]></contactPerson>" + "\n" );
        buf.append ( "<address1><![CDATA[" + address.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + address.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + address.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + address.getAddress4 () + "]]></address4>" + "\n" );

        // Added by Prabhanjan (12 May 2004)
        buf.append ( "<city><![CDATA["+ address.getCity () + "]]></city>" + "\n" );
        buf.append ( "<stateZipCountry><![CDATA[" );
        if(address.getState ()!=null && !(address.getState ().equals("")))
        {
            buf.append(address.getState ());
        }
        if(address.getZipCode()!=null && !(address.getZipCode().equals("")))
        {
            if(address.getState ()!=null && !(address.getState ().equals("")))
            {
                buf.append(" - ");
            }
            buf.append(address.getZipCode());
        }
        if(address.getCountry ()!=null && !(address.getCountry ().equals("")))
        {
            if((address.getZipCode()!=null && !(address.getZipCode().equals("")))||(address.getState ()!=null && !(address.getState ().equals(""))))
            {
                buf.append(", ");
            }
            buf.append(address.getCountry ());
        }
        buf.append ( "]]></stateZipCountry>" + "\n" );

        buf.append ( "<phone><![CDATA[" + ( address.getPhoneNumber () != null && !address.getPhoneNumber().equals("") ?  "Tel:"+ address.getPhoneNumber () : "" ) + "]]></phone>" + "\n" );
        buf.append ( "<cell><![CDATA[" + ( address.getCellNumber () != null && !address.getCellNumber().equals("") ?  "Cell:"+address.getCellNumber () : "" ) + "]]></cell>" + "\n" );
        buf.append ( "<fax><![CDATA[" + ( address.getFaxNumber () != null && !address.getFaxNumber().equals("") ?  "Fax:" + address.getFaxNumber () : "" ) + "]]></fax>" + "\n" );
        buf.append ( "<email><![CDATA[" + ( address.getEmail () != null && !address.getEmail().equals("") ?  "EMail:" + address.getEmail () : "" ) + "]]></email>" + "\n" );
        buf.append ( "</orderByAddress>" + "\n" );

        buf.append ( "<billToAddress>" + "\n" );
        // Modified by veeru on 5th May 2004
        if( quotation.getBillingAddressAsObject().getContactPerson() != null && quotation.getCustomerName().trim().length() !=0 )
        {
            if( ! quotation.getBillingAddressAsObject().getContactPerson().equals( quotation.getCustomerName() ) )
            {
                buf.append ( "<name><![CDATA[" + customerName + "]]></name>" + "\n" );
            }
        }
        buf.append ( "<contactPerson><![CDATA[" + address.getContactPerson () + "]]></contactPerson>" + "\n" );
        buf.append ( "<address1><![CDATA[" + address.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + address.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + address.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + address.getAddress4 () + "]]></address4>" + "\n" );

        // Added by Prabhanjan (12 May 2004)
        buf.append ( "<city><![CDATA["+ address.getCity () + "]]></city>" + "\n" );
        buf.append ( "<stateZipCountry><![CDATA[" );
        if(address.getState ()!=null && !(address.getState ().equals("")))
        {
            buf.append(address.getState ());
        }
        if(address.getZipCode()!=null && !(address.getZipCode().equals("")))
        {
            if(address.getState ()!=null && !(address.getState ().equals("")))
            {
                buf.append(" - ");
            }
            buf.append(address.getZipCode());
        }
        if(address.getCountry ()!=null && !(address.getCountry ().equals("")))
        {
            if((address.getZipCode()!=null && !(address.getZipCode().equals("")))||(address.getState ()!=null && !(address.getState ().equals(""))))
            {
                buf.append(", ");
            }
            buf.append(address.getCountry ());
        }
        buf.append ( "]]></stateZipCountry>" + "\n" );

        buf.append ( "<phone><![CDATA[" + ( address.getPhoneNumber () != null && !address.getPhoneNumber().equals("") ?  "Tel:"+ address.getPhoneNumber () : "" ) + "]]></phone>" + "\n" );
        buf.append ( "<cell><![CDATA[" + ( address.getCellNumber () != null && !address.getCellNumber().equals("") ?  "Cell:"+address.getCellNumber () : "" ) + "]]></cell>" + "\n" );
        buf.append ( "<fax><![CDATA[" + ( address.getFaxNumber () != null && !address.getFaxNumber().equals("") ?  "Fax:" + address.getFaxNumber () : "" ) + "]]></fax>" + "\n" );
        buf.append ( "<email><![CDATA[" + ( address.getEmail () != null && !address.getEmail().equals("") ?  "EMail:" + address.getEmail () : "" ) + "]]></email>" + "\n" );

        buf.append ( "</billToAddress>" + "\n" );

        address = quotation.getShippingAddressAsObject ();

        buf.append ( "<shipToAddress>" + "\n" );
        buf.append ( "<name><![CDATA[" + quotation.getCustomerName () + "]]></name>" + "\n" );
        buf.append ( "<contactPerson><![CDATA[" + address.getContactPerson () + "]]></contactPerson>" + "\n" );
        buf.append ( "<address1><![CDATA[" + address.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + address.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + address.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + address.getAddress4 () + "]]></address4>" + "\n" );

        // Added by Prabhanjan (12 May 2004)
        buf.append ( "<city><![CDATA["+ address.getCity () + "]]></city>" + "\n" );
        buf.append ( "<stateZipCountry><![CDATA[" );
        if(address.getState ()!=null && !(address.getState ().equals("")))
        {
            buf.append(address.getState ());
        }
        if(address.getZipCode()!=null && !(address.getZipCode().equals("")))
        {
            if(address.getState ()!=null && !(address.getState ().equals("")))
            {
                buf.append(" - ");
            }
            buf.append(address.getZipCode());
        }
        if(address.getCountry ()!=null && !(address.getCountry ().equals("")))
        {
            if((address.getZipCode()!=null && !(address.getZipCode().equals("")))||(address.getState ()!=null && !(address.getState ().equals(""))))
            {
                buf.append(", ");
            }
            buf.append(address.getCountry ());
        }
        buf.append ( "]]></stateZipCountry>" + "\n" );

        buf.append ( "<phone><![CDATA[" + ( address.getPhoneNumber () != null && !address.getPhoneNumber().equals("") ?  "Tel:"+ address.getPhoneNumber () : "" ) + "]]></phone>" + "\n" );
        buf.append ( "<cell><![CDATA[" + ( address.getCellNumber () != null && !address.getCellNumber().equals("") ?  "Cell:"+address.getCellNumber () : "" ) + "]]></cell>" + "\n" );
        buf.append ( "<fax><![CDATA[" + ( address.getFaxNumber () != null && !address.getFaxNumber().equals("") ?  "Fax:" + address.getFaxNumber () : "" ) + "]]></fax>" + "\n" );
        buf.append ( "<email><![CDATA[" + ( address.getEmail () != null && !address.getEmail().equals("") ?  "EMail:" + address.getEmail () : "" ) + "]]></email>" + "\n" );
        buf.append ( "</shipToAddress>" + "\n" );

        buf.append ( "<information>" + "\n" );
        buf.append ( "<labelOrderDate>" + requestedOrderDateLabel + "</labelOrderDate>");
        buf.append("<labelSalesPerson>" + requestedSalesPersonLabel + "</labelSalesPerson>");
        buf.append("<labelRegionalRep>" + requestedRegionalRepLabel + "</labelRegionalRep>");
        //buf.append ( "<customerQ><![CDATA[" + quotation.getCustomerPO () + "]]></customerQ>" + "\n" );
        buf.append ( "<quotation><![CDATA[" + quotation.getQuotationNo() + "]]></quotation>" + "\n" );
        buf.append ( "<orderDate><![CDATA[" + quotation.getBookingdateAsString () + "]]></orderDate>" + "\n" );
        buf.append ( "<expireDate><![CDATA[" + quotation.getExpiryDate()  + "]]></expireDate>" + "\n" );
        buf.append ( "<shipVia><![CDATA[" + quotation.getShippingMethod () + "]]></shipVia>" + "\n" );
        buf.append ( "<salesPerson><![CDATA[" + quotation.getSalesPerson () + "]]></salesPerson>" + "\n" );
        buf.append ( "<regionalRep><![CDATA[" + quotation.getRegionalRep () + "]]></regionalRep>" + "\n" );
        buf.append ( "<delTerms><![CDATA[" + quotation.getDeliveryTerms () + "]]></delTerms>" + "\n" );
        buf.append ( "<payTerms><![CDATA[" + ( quotation.getShippingTerms ().trim ().equals ( "-1" ) ? "" : quotation.getShippingTerms () ) + "]]></payTerms>" + "\n" );
        buf.append ( "</information>" + "\n" );
        buf.append ( "<comments><![CDATA[" + quotation.getComments () + "]]></comments>" + "\n" );

        LineItem lineItem = null;
        //int size = presentList.size ();

        ArrayList presentListWithSubtotals = QuotationViewAction.loadLineItemsWithSubTotals ( presentList );

        buf.append ( "<lineItems>" + "\n" );

        //Added by Prabhanjan on 15 Mar 2004
        String mfgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mfgPartNumber" );
        if ( mfgPartNumberLabel == null )
        {
            mfgPartNumberLabel = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
        }

        //Added by Prabhanjan on 15 Mar 2004
        String customerPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.customerPartNumber" );
        if ( customerPartNumberLabel == null )
        {
            customerPartNumberLabel = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
        }
        String requestedPriceLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.requestedPrice" );
        if ( requestedPriceLabel == null )
        {
            requestedPriceLabel = Labels.DEFAULT_REQUESTED_PRICE_LABEL;
        }
        String custResalePriceLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.customerResalePrice" );
        if ( custResalePriceLabel == null )
        {
            custResalePriceLabel = Labels.DEFAULT_CUST_RESALE_PRICE_LABEL;
        }
        String priceLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.price" );
        if ( priceLabel == null )
        {
            priceLabel = Labels.DEFAULT_SUGG_RESALE_PRICE_LABEL;
        }
        String suggResalePriceLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.suggestedResalePrice" );
        if ( suggResalePriceLabel == null )
        {
            suggResalePriceLabel = Labels.DEFAULT_SUGG_RESALE_PRICE_LABEL;
        }

        buf.append ( "<labelMfgPartNumber><![CDATA[" + mfgPartNumberLabel + "]]></labelMfgPartNumber>" );
        buf.append ( "<labelCustPartNumber><![CDATA[" + customerPartNumberLabel + "]]></labelCustPartNumber>" );
        int subtotalColspan = 8;
        if(ConfigManager.isShowQuoteMinOrderQty()) {
            subtotalColspan++;
            buf.append ( "<labelMinOrderQuantity><![CDATA[" + "Min Order Qty" + "]]></labelMinOrderQuantity>" );
        }
        if ( quotation.isDistributor() )
        {
            if ( ConfigManager.isShowQuoteRequestedPrice() )
            {
                subtotalColspan++;
                buf.append ( "<labelRequestedPrice><![CDATA[" + requestedPriceLabel + "]]></labelRequestedPrice>" );
            }
            if ( ConfigManager.isShowQuoteCustResalePrice() )
            {
                subtotalColspan++;
                buf.append ( "<labelCustResalePrice><![CDATA[" + custResalePriceLabel + "]]></labelCustResalePrice>" );
            }
            if ( ConfigManager.isShowQuoteSuggResalePrice() )
            {
                subtotalColspan++;
                buf.append ( "<labelSuggResalePrice><![CDATA[" + suggResalePriceLabel + "]]></labelSuggResalePrice>" );
            }
        }
        buf.append ( "<noOfDynaColoums><![CDATA[" + (subtotalColspan-8) + "]]></noOfDynaColoums>" );
        buf.append ( "<labelPrice><![CDATA[" + priceLabel + "]]></labelPrice>" );
        buf.append ( "<subTotaColSpan>" + subtotalColspan + "</subTotaColSpan>\n" );

        //Modified by Prabhanjan on 07 Mar 2004
        for ( int i = 0; i < presentListWithSubtotals.size (); i++ )
        {
            HashMap hashMap = ( HashMap ) presentListWithSubtotals.get ( i );
            Iterator iterator = hashMap.keySet ().iterator ();
            while ( iterator.hasNext () )
            {
                ArrayList list = ( ArrayList ) iterator.next ();
                // Modified by Prabhanjan (3 Arp 2004)
                SubTotal subTotal = ( SubTotal ) hashMap.get ( list );
                String subTotalQty = subTotal.getSubTotalQty ();
                String subTotalAmt = subTotal.getSubTotalAmt ();


                int size = list.size ();
                buf.append ( "<group>" + "\n" );

                for ( int j = 0; j < size; j++ )
                {
                    lineItem = ( LineItem ) list.get ( j );
                    buf.append ( "<lineItem>" + "\n" );
                    buf.append ( "<poLineItem><![CDATA[" + lineItem.getPoLineItemNo () + "]]></poLineItem>" + "\n" );
                    buf.append ( "<reqQty><![CDATA[" + lineItem.getQuantity () + "]]></reqQty>" + "\n" );
                    buf.append ( "<minOrderQuantity><![CDATA[" + lineItem.getMinOrderQty () + "]]></minOrderQuantity>" + "\n" );
                    buf.append ( "<um><![CDATA[" + "ea" + "]]></um>" + "\n" );
                    buf.append ( "<mfgPartNumber><![CDATA[" + lineItem.getManufacturingPartNo () + "]]></mfgPartNumber>" + "\n" );
                    buf.append ( "<customerPartNumber><![CDATA[" + lineItem.getCustomerPartNo () + "]]></customerPartNumber>" + "\n" );
                    buf.append ( "<description><![CDATA[" + lineItem.getDescription () + "]]></description>" + "\n" );
                    buf.append ( "<requestDate><![CDATA[" + lineItem.getRequestDate () + "]]></requestDate>" + "\n" );
                    buf.append ( "<leadTime><![CDATA[" + (lineItem.getLeadTime ()==null ? "" : lineItem.getLeadTime()) + "]]></leadTime>" + "\n" );
                    buf.append ( "<taxable><![CDATA[" + lineItem.getIsTaxableAsString () + "]]></taxable>" + "\n" );
                    buf.append ( "<unitPrice><![CDATA[" + lineItem.getUnitPriceAsString () + "]]></unitPrice>" + "\n" );
                    buf.append ( "<requestedPrice><![CDATA[" + lineItem.getReqPriceAsString () + "]]></requestedPrice>" + "\n" );
                    buf.append ( "<custResalePrice><![CDATA[" + lineItem.getCustResaleAsString () + "]]></custResalePrice>" + "\n" );
                    buf.append ( "<suggResalePrice><![CDATA[" + lineItem.getSuggResaleAsString () + "]]></suggResalePrice>" + "\n" );
                    buf.append ( "<extendedPrice><![CDATA[" + lineItem.getExtendedPriceForQuoteAsString () + "]]></extendedPrice>" + "\n" );
                    buf.append ( "</lineItem>" + "\n" );
                }
                buf.append ( "<subTotalQty><![CDATA[" + subTotalQty + "]]></subTotalQty>" + "\n" );
                buf.append ( "<subTotalAmt><![CDATA[" + subTotalAmt + "]]></subTotalAmt>" + "\n" );
                buf.append ( "</group>" + "\n" );
            }
        }
        buf.append ( "</lineItems>" + "\n" );
        String endUserLabel = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.sales.endUser");
        if ( endUserLabel == null )
        {
            endUserLabel = "Error in End User";
        }
        String endCustomerLabel = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.sales.endCustomer");
        if ( endCustomerLabel == null )
        {
            endCustomerLabel = "Error in End Customer";
        }

        buf.append ( "<endCustomerLabel><![CDATA[" + endCustomerLabel + "]]></endCustomerLabel>" );
        buf.append ( "<endUserLabel><![CDATA[" + endUserLabel + "]]></endUserLabel>" );
        buf.append ( "<endCustomer><![CDATA[" + quotation.getOdm() + "]]></endCustomer>" + "\n" );
        buf.append ( "<endUser><![CDATA[" + quotation.getEndCustomer() + "]]></endUser>" + "\n" );
        buf.append ( "<total><![CDATA[" + quotation.getFinalSubTotalAsString () + "]]></total>" + "\n" );
        buf.append ( "<salesTax><![CDATA[" + quotation.getSalesTaxAsString () + "]]></salesTax>" + "\n" );
        buf.append ( "<freight><![CDATA[" + quotation.getFrieghtAsString () + "]]></freight>" + "\n" );
        buf.append ( "<misc name=\"" + quotation.getMiscName () + "\"><![CDATA[" + quotation.getMiscAsString () + "]]></misc>" + "\n" );
        buf.append ( "<balanceDue><![CDATA[" + quotation.getFinalOrderTotalAsString () + "]]></balanceDue>" + "\n" );

        buf.append ( "<clientName><![CDATA[" + quotation.getClientName () + "]]></clientName>" );
        buf.append ( "<clientAddress><![CDATA[" + SalesOrder.getClientAddressToLoad ( clientAddress ) + "]]></clientAddress>" );
        if(ConfigManager.getShowTermsLabel() )
        {
            buf.append ( "<notes><termsLabel>" + Constants.TERMS_LABEL + "</termsLabel></notes>" );
        }
        ArrayList list = SalesDAO.loadTermsAndConditionsAsList ();
        if ( list != null )
        {
            buf.append ( "<termsAndConditions>" + "\n" );
            buf.append("<isTermsFromDB>"+ ConfigManager.getShowTermsFromDB() + "</isTermsFromDB>");
             buf.append ( "<termsPage1>" + ConfigManager.getChipTracImagesDir () + "/Terms and Condition of Sale.jpg</termsPage1>" + "\n" );
            buf.append ( "<termsfromdb>" + "\n" );

            for ( int i = 0; i < list.size (); i++ )
            {
                TermsAndConditions terms = ( TermsAndConditions ) list.get ( i );

                buf.append ( "<termAndConditionFromDB>" + "\n" );
                buf.append ( "<title><![CDATA[" + ( i + 1 ) + ". " + terms.getTermsTitle () + " ]]></title>" + "\n" );
                buf.append ( "<description>" + terms.getXMLFormatTerms(terms.getTerms ()) + "</description>" + "\n" );
                buf.append ( "</termAndConditionFromDB>" + "\n" );
            }
            buf.append ( "</termsfromdb>" + "\n" );
            buf.append ( "</termsAndConditions>" + "\n" );
        }
        buf.append ( "</quotationAcknowledgement>" + "\n" );

        return buf.toString ();
    }
}